<template>
    <div>
        <el-card>
            <el-button type="primary" @click="addRole">添加角色</el-button>
        </el-card>

        <el-card>
            <el-table :data="data.list" style="width: 100%">
                <el-table-column fixed prop="roleId" label="id" width="150" />
                <el-table-column prop="roleName" label="昵称" width="220" />
                <el-table-column prop="state" label="菜单权限" width="700">
                    <template #default="{ row, $index }">
                        <el-popconfirm confirm-button-text="了解" v-for="(item, index) in row.userPermissions"
                            :key="index" :title="data.menuTipInfo" hide-icon="true" width="240">
                            <template #reference>
                                <el-button @click="handleClick(item.menuId)">{{ item.menuName }}</el-button>
                            </template>
                        </el-popconfirm>
                    </template>
                </el-table-column>

                <el-table-column fixed="right" label="操作" min-width="120">
                    <template #default="{ row, $index }">
                        <el-button link type="primary" size="small" @click="editMenu(row)">编辑</el-button>
                        <el-button link type="primary" size="small">
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>

        <!-- 编辑dialog -->
        <el-dialog v-model="data.dialogFormVisible" title="菜单权限" width="500" :before-close="closeDdit">
            <el-table :data="data.tipMenu">
                <el-table-column prop="roleId" label="id" width="150" />
                <el-table-column prop="roleName" label="昵称" width="150" />
            </el-table>
            <div class="checkedMenu">
                <el-checkbox v-model="data.checkAll" :indeterminate="data.isIndeterminate"
                    @change="handleCheckAllChange">
                    全选
                </el-checkbox>
                <el-checkbox-group v-model="data.checkedMenus" @change="handleCheckedCitiesChange">
                    <el-checkbox v-for="menu in data.menus" :key="menu.menuId" :label="menu.menuId">
                        {{ menu.menuName }}
                    </el-checkbox>
                </el-checkbox-group>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="data.dialogFormVisible = false">取消</el-button>
                    <el-button type="primary" @click="makeSure">
                        确定
                    </el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 添加dialog -->
        <el-dialog v-model="data.dialogVisible" title="添加角色" width="500" :before-close="handleClose">
            <el-form :model="data.form" ref="ruleFormRef" :rules="data.rules"  label-width="auto" style="max-width: 600px">
                <el-form-item label="昵称" prop="roleName">
                    <el-input v-model="data.form.roleName" placeholder="请输入要添加的角色昵称" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="data.dialogVisible = false">取消</el-button>
                    <el-button  type="primary"  @click="makeSureAddRole">确定</el-button>
                </div>
            </template>
        </el-dialog>

    </div>
</template>

<script setup>
import { addRoleInfo, editRoleMenu, getAllParentMenu, getMenuChildInfo, getRoleInfo } from '@/api/menu';
import { ElMessage } from 'element-plus';
import { onMounted, reactive, ref } from 'vue';


onMounted(() => {
    load()
})

const data = reactive({
    list: [],                       // 角色信息
    menuTipInfo: '',                // 提示信息
    dialogFormVisible: false,       // 编辑角色弹窗
    dialogVisible: false,           // 添加角色弹窗
    tipMenu: [],                    // 提示菜单 --- 包含角色Id 和 角色名
    form: {},                       // 添加角色表单
    menus: [],                      // 可选的菜单
    checkedMenus: [],               // 所有选中的菜单
    isIndeterminate: false,         // 是否半选
    checkAll: false,                // 全选

    rules: {
        roleName: [
            { required: true, message: '角色昵称不能为空', trigger: 'blur' },
        ]
    }
})

const ruleFormRef = ref()

// 是否全选
const handleCheckAllChange = (val) => {
    data.checkedMenus = val ? data.menus.map(menu => menu.menuId) : []
    data.isIndeterminate = false
}

// 选中对应的菜单
const handleCheckedCitiesChange = (value) => {
    const checkedCount = value.length
    data.checkAll = checkedCount === data.menus.length
    data.isIndeterminate = checkedCount > 0 && checkedCount < data.menus.length
}

// 提示路由信息
const handleClick = async (parentId) => {
    data.menuTipInfo = ''
    const response = await getMenuChildInfo(parentId)
    if (!response.data.length || response.data == null) {
        data.menuTipInfo = '当前菜单即为路由入口'
        return
    }
    const menuNames = response.data.map(item => item.menuName)
    const menuNamesString = menuNames.join(", ")
    data.menuTipInfo = menuNamesString
}

// 编辑
const editMenu = (row) => {
    data.dialogFormVisible = true
    data.tipMenu = [
        {
            roleName: row.roleName,
            roleId: row.roleId
        }
    ]
    // 根据角色信息 ---> 渲染选中的菜单权限
    data.checkedMenus = row.userPermissions.map(item => item.menuId)
    if (data.checkedMenus.length) {
        data.isIndeterminate = true
        if (data.checkedMenus.length === data.menus.length) {
            data.checkAll = true
            data.isIndeterminate = false
        }
    } else {
        return
    }
}

// 点击 ---> X ---> 关闭编辑对话框
const closeDdit = () => {
    data.checkedMenus = []
    data.isIndeterminate = false
    data.checkAll = false
    data.dialogFormVisible = false
}

// 编辑 ---> 确定 async
const makeSure = async () => {
    console.log(data.checkedMenus)
    let menuRole = []
    data.checkedMenus.forEach(item => {
        menuRole.push(item)
    })
    const response = await editRoleMenu(data.tipMenu[0].roleId, menuRole.join(", "))
    if (response.code == '200') {
        ElMessage({
            type: 'success',
            message: '编辑成功',
        })
    }
    closeDdit()
    load()
}

// 添加角色 --- 对话框
const addRole = () => {
    if (ruleFormRef.value) {
        ruleFormRef.value.resetFields()
    }
    data.dialogVisible = true
}

// 点击 ---> X ---> 关闭添加对话框
const handleClose = () => {
    data.form.roleName = ''
    data.dialogVisible = false
}

// 添加角色 --- 确定按钮
const makeSureAddRole = async () => {
    data.dialogVisible = false
    ruleFormRef.value.validate((valid) => {
        if (!valid) {
            ElMessage({
                type: 'warning',
                message: '表单有误',
            }) 
            return
        }
    })

    const response = await addRoleInfo(data.form)
    if (response.code == '200') {
        ElMessage({
            type: 'success',
            message: '新增成功',
        })
    } else {
        ElMessage({
            type: 'warning',
            message: response.msg,
        })
    }
    load()
}

// 
const load = async () => {
    const response = await getRoleInfo()
    data.list = response.data

    const parentMenuResponse = await getAllParentMenu()
    data.menus = parentMenuResponse.data
}


</script>

<style scoped>
* {
    padding: 10px;
}

.checkedMenu {
    border: 1px solid #DDDDDD;
}
</style>